//
//  OBTableViewController.m
//  XZXSchool
//
//  Created by obally on 2017/10/26.
//  Copyright © 2017年 obally. All rights reserved.
//

#import "OBTableViewController.h"
#import "UIScrollView+MHRefresh.h"

@interface OBTableViewController ()<UIGestureRecognizerDelegate>
///the tableView for tableView controller
@property(nonatomic,readwrite,weak) UITableView *tableView;
/// tableView 的内容缩进  默认UIEdgeInsetsMake(64,0,0,0)
@property(nonatomic,readwrite,assign) UIEdgeInsets contentInset;
@property(nonatomic,strong,readonly) OBTableViewModel *viewModel;

@end

@implementation OBTableViewController
@dynamic viewModel;

- (void)dealloc
{
    _tableView.dataSource = nil;
    _tableView.delegate = nil;
}
- (instancetype)initWithViewModel:(OBViewModel *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self) {
        if ([viewModel shouldRequestRemoteDataOnViewDidLoad]) {
            @weakify(self);
            [[self rac_signalForSelector:@selector(viewDidLoad)]subscribeNext:^(id x) {
                @strongify(self);
                ///请求第一页的网络数据
//                [self.viewModel.requestRemoteDataCommand execute:@1];
            }];
        }
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    //设置子控件
    [self _su_setupSubViews];
}
- (void)bindViewModel
{
    [super bindViewModel];
    @weakify(self);
    [[[RACObserve(self.viewModel, dataSource) distinctUntilChanged] deliverOnMainThread]subscribeNext:^(id x) {
        @strongify(self);
        //dataSource 发生改变 刷新数据
        [self reloadData];
    }];
    /// 隐藏emptyView
    [self.viewModel.requestRemoteDataCommand.executing subscribeNext:^(NSNumber *executing) {
        @strongify(self)
        UIView *emptyDataSetView = [self.tableView.subviews.rac_sequence objectPassingTest:^(UIView *view) {
            return [NSStringFromClass(view.class) isEqualToString:@"DZNEmptyDataSetView"];
        }];
        emptyDataSetView.alpha = 1.0 - executing.floatValue;
    }completed:^{
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)_su_setupSubViews
{
    // set up tableView
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:self.viewModel.style];
    tableView.backgroundColor = self.view.backgroundColor;
    tableView.tableFooterView = [[UIView alloc]init];
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    self.tableView = tableView;
    
    tableView.contentInset  = self.contentInset;
    tableView.emptyDataSetDelegate = self;
    tableView.emptyDataSetSource = self;
//    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.estimatedRowHeight = 40;
    tableView.estimatedSectionHeaderHeight = 0;
    tableView.estimatedSectionFooterHeight = 0;
    // 注册cell
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    
    if (self.viewModel.shouldPullDownToRefresh) {
        ///下拉刷新
        @weakify(self);
        [self.tableView mh_addHeaderRefresh:^(MJRefreshNormalHeader *header){
            @strongify(self);
            [self tableViewDidTriggerHeaderRefresh];
        }];
         [self.tableView.mj_header beginRefreshing];
    }
    if (self.viewModel.shouldPullUpToLoadMore) {
        ///上拉加载
        @weakify(self);
        [self.tableView mh_addFooterRefresh:^(MJRefreshAutoNormalFooter *footer) {
            @strongify(self);
            [self tableViewDidTriggerFooterRefresh];
        }];
    }
}
#pragma mark - 上下拉刷新事件
///下拉事件
- (void)tableViewDidTriggerHeaderRefresh
{
    @weakify(self);
    [[[self.viewModel.requestRemoteDataCommand execute:@1]deliverOnMainThread]subscribeNext:^(id x) {
        @strongify(self);
        self.viewModel.page = 1;
        ///重置没有更多的状态
        if ([x isKindOfClass:[NSArray class]]) {
            NSArray *array = (NSArray *)x;
            if ((array.count != self.viewModel.page*self.viewModel.perPage)) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else
                [self.tableView.mj_footer resetNoMoreData];
        }
    }error:^(NSError *error) {
        @strongify(self);
        /// 已经在bindViewModel中添加了对viewModel.dataSource的变化的监听来刷新数据,所以reload = NO即可
        [self.tableView.mj_header endRefreshing];
    } completed:^{
        @strongify(self)
        /// 已经在bindViewModel中添加了对viewModel.dataSource的变化的监听来刷新数据,所以只要结束刷新即可
        [self.tableView.mj_header endRefreshing];
        /// 请求完成
        [self _requestDataCompleted];
    }];
    
}
///上拉拉加载更多
- (void)tableViewDidTriggerFooterRefresh
{
    @weakify(self);
    [[[self.viewModel.requestRemoteDataCommand execute:@(self.viewModel.page +1)]deliverOnMainThread]subscribeNext:^(id x) {
        @strongify(self);
        self.viewModel.page += 1;
    }error:^(NSError *error) {
        @strongify(self);
        [self.tableView.mj_footer endRefreshing];
    } completed:^{
        @strongify(self);
        [self.tableView.mj_footer endRefreshing];
//        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        /// 请求完成
        [self _requestDataCompleted];
    }];
}
#pragma mark - 辅助方法
- (void)_requestDataCompleted
{
    NSUInteger count = 0;
    count = self.viewModel.dataSource.count;
    if (count < self.viewModel.page*self.viewModel.perPage) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }else {
        [self.tableView.mj_footer endRefreshing];
    }
}
#pragma mark - sub class can override it
- (UIEdgeInsets)contentInset{
    return UIEdgeInsetsMake(OB_APPLICATION_TOP_BAR_HEIGHT, 0, 0, 0);
}

/// reload tableView data
- (void)reloadData
{
    [self.tableView reloadData];
}

/// duqueueReusavleCell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
    return [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
}

/// configure cell data
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object {}

/// 申请寄售
- (void)applyConsign{};
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.viewModel.shouldMultiSections) return self.viewModel.dataSource ? self.viewModel.dataSource.count : 0;
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.viewModel.shouldMultiSections) return [self.viewModel.dataSource[section] count];
    
    return self.viewModel.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    
    // fetch object
    id object = nil;
    if (self.viewModel.shouldMultiSections) object = self.viewModel.dataSource[indexPath.section][indexPath.row];
    if (!self.viewModel.shouldMultiSections) object = self.viewModel.dataSource[indexPath.row];
    
    /// bind model
    [self configureCell:cell atIndexPath:indexPath withObject:(id)object];
    return cell;
}


#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // execute commond
    [self.viewModel.didSelectCommand execute:indexPath];
}


@end
